import { getApplyCount, getContactList, getNewFriend } from "@/api/contacts";
import { defineStore } from "pinia";
import { ref } from 'vue'

export const useContactsStore = defineStore('contacts', () => {
    // 联系人列表
    const contacts = ref([]);

    // 添加好友列表
    const applyList = ref([]);

    // 新好友数量
    const newFriendCount = ref(0);

    // 设置联系人列表
    const setContacts = (data) => {
        contacts.value = data;
    }

    // 添加好友List
    const setApplyList = (data) => {
        applyList.value = data;
    }

    // 添加好友
    const addFriend = (data) => {
        applyList.value.push(data);
    }

    // 添加联系人
    const addContact = (data) => {
        contacts.value.push(data);
    }

    // 删除联系人
    const removeContact = (id) => {
        contacts.value = contacts.value.filter(item => item.id !== id);
    }

    // 更新联系人
    const updateContact = (data) => {
        contacts.value = contacts.value.map(item => {
            if (item.id === data.id) {
                return data;
            }
            return item;
        });
    }

    // 获取好友申请数量
    const getApplyListCount = async (userId) =>  {
        const res = await getApplyCount(userId)
        newFriendCount.value = parseInt(res.data.data, 10);
    }

    // 获取最新的好友申请数据
    const getApplyList = async (userId) => {
        const res = await getNewFriend(userId)
        if (res?.data?.rows) {
            setApplyList(res.data.rows)
        }
    }

    // 设置新好友数量
    const setNewFriendCount = (count) => {
        newFriendCount.value = count
    }

    // 获取最新好友
    const getContacts = async (userId) => {
        const res = await getContactList(userId)
        if (res?.data?.rows) {
            setContacts(res.data.rows)
        }
    }

    return {
        contacts,
        applyList,
        setApplyList,
        addFriend,
        setContacts,
        addContact,
        removeContact,
        updateContact,
        getApplyListCount,
        getApplyList,
        newFriendCount,
        setNewFriendCount,
        getContacts
    }
},{
    persist: true
});